import React, { useState, useEffect } from 'react';
import { Button, Input, message, Select, Switch } from 'antd';
import { PopupScript } from '../utils/connect.js';
import { Card } from 'antd';
import { List, Typography, Divider } from 'antd';
import 'antd/dist/antd.css';
import parse from 'url-parse';
import { inject, observer, Provider } from 'mobx-react';
import {createMainStore, IMainStore} from '../../stores'

@inject('store')
@observer
class Popup extends React.Component<{
  store: IMainStore
}> {
  componentDidMount(){
    const {store} = this.props;
    chrome.storage.sync.get("devHost", ({devHost})=> {
      if (!chrome.runtime.lastError) {
        console.log(devHost);
        if(devHost){
          store.setDevHost(devHost);
        }
      }
    });


    chrome.storage.sync.get("mfswitch", ({mfswitch})=> {
      if (!chrome.runtime.lastError) {
        store.setMFSwitch(mfswitch); 
      }
    });
  }


  onChange = () => {
    PopupScript.send({
      type: 'dayoneDev',
      data: {},
      cb: res => {
        console.log('res==', res)
      }
    })
  }

  saveLocalDomain = (e)=>{
    const {store} = this.props;
    store.cacheDevHost()
  }

  changeHost = (e)=>{
    const {store} = this.props;
    store.setDevHost(e.target.value);
  }

  changeWsConfig = (key, value)=>{
    const {store} = this.props;
    store.setLoginConfig(key,value);
  }

  autoLogin = ()=>{
    const {store} = this.props;
    let msg = {
      type: 'autologin',
      data:{
        ...store.wsconfig,
        host: store.devHost
      } ,
      cb: res => {
        console.log('res==', res)
      }
    }
    chrome.runtime.sendMessage(msg,(response)=>{
      console.log('res==', response)
    })
  }

  disconnect(){
    const {store} = this.props;
    store.setLifeCycleState(false);
    chrome.runtime.sendMessage({
      type:'closews',
    },(msg)=>{
      
    })
  }
  connect(){
    const {store} = this.props;
    const uri = parse(store.devHost);
    chrome.runtime.sendMessage({
      type:'connectws',
      host: `${uri.hostname.split(":")[0]}:${store.wsconfig.port}`
    },(msg)=>{
      const {success, cookie} = msg;
      console.log('msg:',msg)
      if(success){
        store.setLifeCycleState(success);
      }else if(cookie){
        store.setCookie(cookie);
      }
    })
  }
  render() {
    const {store} = this.props;
    return (
      <Card title="Neo开发助手(Chrome版)" bordered={false} style={{ height: 600, width: '100%' }}>
        <div>
          <div>
            <h3>功能一、手动登录，自动复制Cookie：</h3>
            <p>1.输入本地开发环境地址，注意：开发地址如果是localHost，文本框填localHost</p>
            <p>2.打开浏览器登录目标环境</p>
            <p>3.检查本地webpack配置中proxy的target是否是目标环境</p>
          </div>
          <Input style={{width:'80%', marginTop: 5}} value={store.devHost} onChange={this.changeHost} onBlur={this.saveLocalDomain}/>
          <Divider/>
          <div>
            <h3>功能二、组件模块联邦代理</h3>
            <div><span>开启/关闭</span> <Switch checked={store.mfSwitch} onChange={()=>store.toggleMfSwitch()}/></div>
          </div>
          <Divider/>
          <div>
            <h3>功能三、地址栏追加字符串(用于旧版ingage-web)</h3>
            <Button type='primary'  onClick={this.onChange}>develop_mode=1&resDomain=https://localhost</Button>
          </div>
          {/* <div>
            <h3>三、服务器端T出后，自动登录</h3>
            <div>
              用户名：<Input value={store.wsconfig.username}  onChange={(e)=>this.changeWsConfig('username',e.target.value )}/>
              密码：<Input  value={store.wsconfig.password}  onChange={(e)=>this.changeWsConfig('password',e.target.value )}/>
              租户Id:<Input  value={store.wsconfig.tenantId}  onChange={(e)=>this.changeWsConfig('tenantId',e.target.value )}/>
              登录环境: <Select value={store.wsconfig.env}   onChange={(value)=>this.changeWsConfig('env',value )}>
                <Option value={'cd'}>crm-cd</Option>
                <Option value={'crm'}>crm生产</Option>
                </Select>
              <p>登录地址：{store.wsconfig.loginUrl}</p>
              <div><span>ws端口</span><Input defaultValue={store.wsconfig.port} onChange={(e)=>this.changeWsConfig('port',e.target.value )}/>
               <div>等本地服务启动后点击连接</div>
               <div>连接状态: <p style={{color: !store.wsLifeCycle.connectState?'black':'green'}}>{store.wsLifeCycle.connectState ? '已连接':"未连接"}</p></div>
               <Button onClick={()=>store.wsLifeCycle.connectState? this.disconnect():this.connect()}>{store.wsLifeCycle.connectState? "断开":"连接本地环境"}</Button>
               <Button onClick={()=>this.autoLogin()}>登录</Button>
              </div>
            </div>
          </div> */}
        </div>
      </Card>
    );
  }
}


class PopupWrapper extends React.Component{
  render(){
    const store = createMainStore()
    return (
      <Provider store={store}>
            <Popup store={store}/>
      </Provider>
      )
  }
}

export default PopupWrapper;
